package com.metagurukul.informer.dao;

import java.sql.*;

import com.metagurukul.informer.utility.ConnectionFactory;

public class RegisterUserDAO {


	/**
	 * remove temp user
	 * @param id
	 * @throws SQLException
	 */
	public void deleteTempUser(String id)throws SQLException{
		if(id==null){
			throw new NullPointerException();
		}
		PreparedStatement ps=null;
		Connection con = ConnectionFactory.getInstance();
		String sql = "delete FROM tempUsers WHERE id=?";
		ps=con.prepareStatement(sql);
		ps.setString(1, id);
		ps.executeUpdate();
		
		if(ps!=null){
			ps.close();
		}
		if(con!=null){
			con.close();
		}
	}
	/**
	 * registers user in tempUser table and return password
	 * @param id
	 * @param name
	 * @return
	 * @throws SQLException
	 */
public String registerUser(String id,String name) throws SQLException {
		
		PreparedStatement ps=null;
		String sql = "insert into tempUsers(id,name,password,isadmin) values (?,?,?,?)";
		String password=generatePassword();
		
		Connection con;
		
			con = ConnectionFactory.getInstance();
			ps=con.prepareStatement(sql);
			ps.setString(1,id);
			ps.setString(2,name);
			ps.setString(3,password);
			ps.setBoolean(4, false);
			ps.executeUpdate();
			
			if(ps!=null){
				ps.close();
			}
			if(con!=null){
				con.close();
			}
			
			return password;

		
	}

/**
 * method for update password 
 * @param id
 * @param password
 * @throws SQLException
 */
	public void updatePassword(String id,String password) throws SQLException{
		PreparedStatement ps=null;
		String sql = "UPDATE users SET password=? WHERE id=?";
		Connection con;
		
			con = ConnectionFactory.getInstance();
			ps=con.prepareStatement(sql);
			ps.setString(1,password);
			ps.setString(2,id);
			ps.executeUpdate();
			
			if(ps!=null){
				ps.close();
			}
			if(con!=null){
				con.close();
			}
		
	}
	
	/**
	 * method that generates password
	 * @return password
	 * @throws SQLException
	 */
	private String generatePassword() throws SQLException{
		String password=null;
		Statement st=null;
		ResultSet rs=null;
		String sql="SELECT SUBSTRING(MD5(RAND()) FROM 1 FOR 6) AS password";
		Connection con;
		
			con = ConnectionFactory.getInstance();
			st=con.createStatement();
			rs=st.executeQuery(sql);
			if(rs.next()){
				password=rs.getString(1);
			}
			if(st!=null){
				st.close();
			}
			if(rs!=null){
				rs.close();
			}
			if(con!=null){
				con.close();
			}
		return password;
	}
}
